<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) wangyt <wangtom365@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace App\Models;

use Cache;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class BaseModel extends EloquentModel
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = true;

    /**
     * @var table
     */
    protected $table = '';

    /**
     * constructor.
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function setTableName($tableName = '', $tablePrefix = '')
    {
        $tableList = \Config::get('site-tables.tableName');
        if (empty($tablePrefix)) {
            $tablePrefix = \Config::get('site-tables.tablePrefix');
        }
        $tableName = ! empty($tableList[$tableName]) ? $tableList[$tableName] : '';
        return $this->table = $tablePrefix . $tableName;
    }

    /**
     * 保存.
     *
     * @param array $input
     * @return int
     */
    public function saveData($input = [])
    {
        if ($input instanceof Collection) {
            $input = $input->toArray();
        }

        return self::insertGetId($input);
    }

    /**
     * 保存.
     *
     * @param array $input
     * @param bool $isMulti
     * @return bool|int
     */
    public function insertData($input = [], $isMulti = false)
    {
        if ($input instanceof Collection) {
            $input = $input->toArray();
        }

        if ($isMulti) {
            return self::insert($input);
        }

        return self::insertGetId($input);
    }

    /**
     * 更新.
     *
     * @param array $where
     * @param array $input
     * @return bool
     */
    public function updateData(array $where, array $input = [])
    {
        return self::where($where)->update($input);
    }

    /**
     * @param int $id
     * @param $
     * @return array
     */
    public function getDetailById($id = 0, $isUseCache = true, $cacheMinutes = 60)
    {
        if ($id) {
            $result = $this->findOrFail($id)->toArray();
        }

        return $result;
    }

    /**
     * 列表.
     *
     * @param Collection|null $input
     * @param bool|true       $isUseCache
     * @param int             $cacheMinutes
     *
     * @return Collection
     */
    public function getListData(Collection $input = null, $isUseCache = true, $cacheMinutes = 60)
    {
        // print_r(func_get_args());exit;
        $cacheKey = sprintf('cache_%_%s_%s', $this->table, date('YmdHis'), json_encode(func_get_args()));

        if ($isUseCache === false || ($result = Cache::get($cacheKey)) === null) {
            info('cache: '.$cacheKey);
            if ($input === null) {
                $input = collect([]);
            }
            $where = $input->get('where', []);
            $select = $input->get('select', '*');
            $orderBy = $input->get('orderBy', [$this->primaryKey => 'desc']);
            $limit = $input->get('limit', '20');
            if ($select) {
                $select = is_array($select) ? implode(',', $select) : (string) $select;
            }

            $model = self::select(DB::raw($select));
            // WHERE
            if ($where) {
                foreach ($where as $key => $val) {
                    if (is_array($val)) {
                        $model->whereIn($key, $val);
                    } else {
                        $model->where($key, $val);
                    }
                }
            }
            // ORDER BY
            if ($orderBy && is_array($orderBy)) {
                foreach ($orderBy as $key => $val) {
                    $val = strtoupper($val);
                    if ($val === 'DESC' || $val === 'ASC') {
                        $model->orderBy($key, $val);
                    }
                }
            }
            // $model->orderBy('id', 'desc');
            // LIMIT
            $model->limit($limit);
            // RESULT
            $result = $model->get();

            $result = $result->toArray();

            Cache::put($cacheKey, $result, $cacheMinutes);
        }

        return collect($result);
    }

    /**
     * 列表
     *
     * @param array $where
     * @param string $select
     * @param int $limit
     * @return mixed
     */
    public function getList(array $where = [], $select = '*', $limit = 100)
    {
        $minutes = 0;
        $cacheKey = sprintf('cache_%_%s_%s', $this->table, date('YmdHis'), json_encode(func_get_args()));
        if (($result = Cache::get($cacheKey)) === null) {
            info('cache: '.$cacheKey);
            $select = '*';
            if ($select) {
                $select = is_array($select) ? implode(',', $select) : (string) $select;
            }

            $result = self::select(DB::raw($select))
                ->where($where)
                ->orderBy($this->primaryKey, 'desc')
                ->limit($limit)
                ->get();

            Cache::put($cacheKey, $result, $minutes);
        }

        return $result->toArray();
    }

    /**
     * 获取列表(带分页).
     *
     * @param array  $where
     * @param string $select
     * @param int    $page
     * @param int    $pageSize
     */
    public function getListWithPaginate(array $where = [], $select = '*', $page = 0, $pageSize = 20)
    {
        $minutes = 0;
        $cacheKey = sprintf('cache_%_%s_%s', $this->table, date('YmdHis'), json_encode(func_get_args()));
        if (($result = Cache::get($cacheKey)) === null) {
            info('cache: '.$cacheKey);
            // $result Array(
            //     [per_page] => 15
            //     [current_page] => 1
            //     [next_page_url] => http://wang123.app/link?page=2
            //     [prev_page_url] =>
            //     [from] => 1
            //     [to] => 15
            //     [data] => Array()
            // )
            $select = '*';
            if ($select) {
                $select = is_array($select) ? implode(',', $select) : (string) $select;
            }

            $result = self::select(DB::raw($select))
                ->where($where)
                ->orderBy($this->primaryKey, 'desc')
                ->simplePaginate();

            if ($where) {
                $result->appends($where)->links();
            }

            Cache::put($cacheKey, $result, $minutes);
        }

        return $result->toArray();
    }

    /**
     * @param string $function
     * @param $input
     *
     * @return string
     */
    protected function formatCacheKey($function, $input)
    {
        return sprintf('cache_%s_%s_%s_%s', $this->table, $function, date('Ymd'), md5(json_encode($input)));
    }
}
